import { ElMessageBox, ElMessage } from "element-plus";
import { generateUUID } from "@/utils";
import { updateProductUpdate, getProductDetail } from "@/api/modules/agv";
import { useUtils } from "./useUtils";

export const useEdit = (options: any) => {
  const { formData, id, selectList, appearance, testVideo, isEdit, rules } = options; // ruleFormRef,
  const { transformDataReq, productBaseData, getProductModelAllFn } = useUtils();
  const initData = async () => {
    appearance.value = [];
    testVideo.value = [];
    try {
      const { data } = await getProductDetail({ id });
      const products = await getProductModelAllFn(data.type);
      selectList.value["productModelList"] = products;
      const { result, appearanceTestVideo } = await productBaseData({ selectList }); // keyPart
      data["productDataList"].forEach((item: any) => {
        item.uuid = generateUUID();
      });
      data["productParts"].forEach((item: any) => {
        item.uuid = generateUUID();
        item.lonely = 1;
      });
      data["assemblyInfos"].forEach((item: any) => {
        item.uuid = generateUUID();
        item.lonely = 1;
      });
      // 获取传输的值
      for (const [key, value] of Object.entries(appearanceTestVideo)) {
        console.log(key);
        value.forEach((item: any) => {
          result[item.id].forEach((item2: any) => {
            const obj = data["productDataList"].find((itm: any) => item2.name == itm.remark);
            if (obj) {
              obj.fixed = 1; // 是否固定
              obj.lonely = 1; // 是否独立上传
            }
          });
        });
      }
      // 图片外观 、 测试视频页面结构
      Object.keys(appearanceTestVideo)
        .reverse()
        .forEach((item, index) => {
          const list = data["productDataList"].filter((itm: any) => itm.category == item);
          switch (index) {
            case 0:
              appearanceTestVideo[item].forEach((item2: any) => {
                item2.productDataList = list.filter((itm: any) => itm.categorySub == item2.id);
                appearance.value.push(item2);
              });
              break;
            case 1:
              appearanceTestVideo[item].forEach((item2: any) => {
                item2.productDataList = list.filter((itm: any) => itm.categorySub == item2.id);
                testVideo.value.push(item2);
              });
              break;
          }
        });

      // 关键零部件
      // const keyPartData: any = [];
      // Object.keys(keyPart).forEach(item => {
      //   item &&
      //     keyPart[item].forEach((item2: any) => {
      //       keyPartData.push({
      //         id: "",
      //         remark: "",
      //         partTypeId: item2.param,
      //         partId: "",
      //         partName: "",
      //         code: "",
      //         type: 1,
      //         path: "",
      //         uuid: generateUUID(),
      //         fixed: 1, // 是否固定
      //         lonely: 1 // 是否独立上传
      //       });
      //     });
      // });
      // 合并
      // const fixedList = data["productParts"].filter((itm: any) => itm.fixed == 1);
      // const otherList = data["productParts"].filter((itm: any) => itm.fixed == 0);
      // keyPartData.forEach((item: any) => {
      //   const obj = fixedList.find((itm: any) => itm.partTypeId == item.partTypeId);
      //   if (obj) {
      //     item = obj;
      //   }
      // });
      // data["productParts"] = [...keyPartData, ...otherList];
      formData.value = data;
    } catch (e) {
      console.log(e);
    }
  };

  const handleSubmit = async () => {
    // ruleFormRef.value!.validate(async (valid: Boolean) => {
    //   if (!valid) return;
    try {
      for (const [key, value] of Object.entries(rules.value)) {
        if (!formData.value[key]) {
          console.log(key, value);
          ElMessage({
            message: value[0]["message"],
            type: "error"
          });
          return;
        }
      }
      await updateProductUpdate(transformDataReq(formData.value, appearance.value, testVideo.value));
      ElMessage.success({ message: `编辑车辆成功！` });
      initData();
      isEdit.value = false;
    } catch (error) {
      console.log(error);
    }
    // });
  };

  const handleCancel = () => {
    ElMessageBox.confirm(`是否有数据未保存，确认取消吗?`, "温馨提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      draggable: true
    }).then(() => {
      initData();
      isEdit.value = false;
    });
  };

  return {
    handleSubmit,
    initData,
    handleCancel
  };
};
